package com.lg.java.oom;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 *
 -XX:+PrintGCDetails -Xms10m -Xmx10m -Xss1024k -XX:MetaspaceSize=2m  -XX:MaxDirectMemorySize=5m

 oom都有那些
 堆溢出
 java.lang.OutOfMemoryError: Java heap space

 栈溢出
    java.lang.StackOverflowError

 原空间溢出
    java.lang.OutOfMemoryError: Metaspace

 直接内存溢出
    java.lang.OutOfMemoryError: Direct buffer memory

 创建线程过多  linux默认一个应用最多1024个线程，这个数量是可以调的
    java.lang.OutOfMemoryError: unable to create new native thread

 gc时间过长，98%的时间都用来做gc收回的内存空间不到2%，连续几次这样的gc，就会出错
    java.lang.OutOfMemoryError: GC overhead limit exceeded

 */
public class Base {
    public static void main(String[] args) {
//        stackOverflow();
//        javaHeapSpace();
//        gcOverheadLimit();
//        DirectMemory();
        unableCreateThread();
    }

//    java.lang.StackOverflowError
    public  static void stackOverflow() {
        stackOverflow();
    }

//    java.lang.OutOfMemoryError: Java heap space
    public static  void javaHeapSpace() {
        byte[] bytes = new byte[1024 * 1024 * 1024];
    }

//    java.lang.OutOfMemoryError: GC overhead limit exceeded
    public static void gcOverheadLimit() {
        int i = 0;
        ArrayList<String> arrayList = new ArrayList<>();
        while (true) {
            arrayList.add(String.valueOf(i++));
        }
    }

//  java.lang.OutOfMemoryError: Direct buffer memory
    public static void DirectMemory() {
        ByteBuffer.allocateDirect(1024 * 1024 * 6);
    }

//    java.lang.OutOfMemoryError: unable to create new native thread
    public static void unableCreateThread() {

        while (true) {
            new Thread(()->{
                try {
                    TimeUnit.HOURS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
//    java.lang.OutOfMemoryError: Metaspace
    private static void  metaspaceOverflow() {
        while (true) {
            //todo
        }
    }
}
